import json

import xmltodict

from backend.api.getResult import *
from Common.Common_random import *
from backend.common.common_db import *
import json
# 拼接环境信息
def data_environment_view(environment_id):
    environment_address = Environment.getEnvironmentAddress(environment_id)
    environment_name = Environment.getEnvironmentName(environment_id)
    environment_data = {
        'environment_id':environment_id,
        'environment_address':environment_address[0]['address'],
        'environment_name':environment_name[0]['env_name']
    }
    # print("环境信息拼接为%s" % environment_data)
    return environment_data

# 拼接接口信息
def data_interface_view(interfaces_id):
#     1.取认证信息
    """加密解密 0不走 1走加密解密"""

    interfaces_authentication = Interfaces.getInterfacesAuthentication(interfaces_id)

    if interfaces_authentication == "0":
        interfaces_encryption_url = ''
        interfaces_decrypt_url = ''
    elif interfaces_authentication == "1":
        interfaces_encryption_url = Interfaces.getInterfacesEncryption(interfaces_id)
        interfaces_decrypt_url = Interfaces.getInterfacesDecrypt(interfaces_id)

    else:
        pass
        # print("认证输入错误！")


#     1-1.获取接口的api
    interfaces_api = Interfaces.getInterfacesApi(interfaces_id)

#     2.获取请求方式
    interfaces_method = Interfaces.getInterfacesMethod(interfaces_id)

#  2-2 获取接口名称
    interfaces_name = Interfaces.getInterfacesName(interfaces_id)

#     3.请求接口入参表
#       3-1接口参数类型 + 随机数
    interfaces_param_key = Interfaces_Param.getInterfacesParams(interfaces_id)

    param_list_all = []
    for param_dict in interfaces_param_key:
        param_list = []
        param_list.append(param_dict['param_key'])
        param_list.append(param_dict['param_type'])
        param_list.append(param_dict['random_number'])
        param_list.append(param_dict['random_number_type'])
        param_list_all.append(param_list)

    print(11)
    print(param_list_all)

    # 1.
    param_dict = {}
    for list1 in param_list_all:
        print(list1[1])
        print(type(list1[1]))
        if list1[1] == 'String':  # 0表示字符串
            if list1[2] == '0':  #不生成随机数
                param_dict[list1[0]] = ""

        elif list1[1] == 'Random' and list1[2] == "1":


            if list1[3] == 'Random_Int':  # 生成10位随机数
                print("调生成字符串！！！！！！！！！1")
                random_result = random_number_str(2)
                param_dict[list1[0]] =  random_result

            elif list1[3] == 'Random_Name':  # 生成姓名
                random_name = getName()
                param_dict[list1[0]] = random_name
            elif list1[3] == 'Random_PhoneNo':  # 生成手机号
                random_phone = phoneNORandomGenerator()
                param_dict[list1[0]] = random_phone

            elif list1[3] == 'Random_Email':  # 生成邮箱
                random_email = RandomEmail()
                param_dict[list1[0]] = random_email

            elif list1[3] == 'Random_IDCard':  # 生成身份证
                random_idcard = getRandomIdCard()
                param_dict[list1[0]] = random_idcard

            # 此处添加多种随机数生成方式

            else:
                pass
                # print("随机数类型传值错误")


        elif list1[1] == 'List':
            param_dict[list1[0]] = []
        #     后期完善时间类型及整数类型
        else:
            pass
            # print("类型输入错误")
    # print(param_dict)


    # 3-2.转成json类型
    json_data = json.dumps(param_dict)


#   4.请求头入参表
    testcases_header_key = Interfaces_Header.getInterfacesHeader(interfaces_id)
    header_key_dict = {}
    for testcases_header in testcases_header_key:
        header_key_dict[testcases_header["header_key"]] = testcases_header["header_key_value"]

#     5.请求取值类型
    testcases_apihttptype = Interfaces.getApiHttpType(interfaces_id)
    print("接收到得值：%s"%testcases_apihttptype)

    # 6.isList取值
    testcases_isList = Interfaces.getIsList(interfaces_id)
    print("收到得isList取值：%s"%testcases_isList)

# 7. listPadding取值
    testcases_listPadding = Interfaces.getListPadding(interfaces_id)
    print("收到得testcases_listPadding取值：%s"%testcases_listPadding)




#     5.拼接接口信息
    interface_data = {}
    interface_data['interfaces_id'] = interfaces_id
    interface_data['interfaces_name'] = interfaces_name
    interface_data['api'] = interfaces_api
    interface_data['method'] = interfaces_method
    interface_data['param_data'] = json_data
    interface_data['header_key'] = header_key_dict
    interface_data['interfaces_encryption_url'] = interfaces_encryption_url
    interface_data['interfaces_decrypt_url'] = interfaces_decrypt_url
    interface_data['interfaces_authentication'] = interfaces_authentication
    interface_data['testcases_apihttptype'] = testcases_apihttptype
    interface_data['testcases_isList'] = testcases_isList
    interface_data['testcases_listPadding']  = testcases_listPadding

    content = {
        'interface_data':interface_data
    }
    print('此时的接口拼接为：%s' % content)

    return content,param_list_all

# 案例信息
def data_interface_cases_view(testcase_id,test_interfaces_datas,interfaces_id):
    # 1.用例表：取出测试案例名称
    testcases_case_name = Interfaces_Case.getCaseName(testcase_id)

    # 2用例表：取出用例分类(数据校验，业务逻辑校验，疏通测试)
    testcases_case_type = Interfaces_Case.getCaseType(testcase_id)

    print("断言！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！11")
    print("马嘉璐注意！！！！！！！！！！！！！！")
    print(testcases_case_type)
    if testcases_case_type == "1" or testcases_case_type == "0" or testcases_case_type == "2":
        # 3.用例表：取出校验分类（问题涉及数据库校验,后续加判断）
        testcases_check_type = Interfaces_Case.getCheckType(testcase_id)
        print(testcases_check_type)


        # 3.用例表子表查询：拼接校验关键字+断言类型+预期值

        # 3-1 用例下的所有断言对于的id
        check_ids = Interfaces_Case_Check.getCaseCheckID(testcase_id)
        print(check_ids)
        print("循环中！！！！！！！！！")   #[{'id': 223}, {'id': 224}, {'id': 225}, {'id': 226}]

        out_dict = {}
        for i in check_ids:

            check_id = i['id']

            testcases_check_key = Interfaces_Case_Check.getTestcasesCheckKey(check_id)
            print(testcases_check_key)
            testcases_check_condition = Interfaces_Case_Check.getTestcasesCheckCondition(check_id)
            print(testcases_check_condition)
            testcases_expect_value = Interfaces_Case_Check.getTestcasesExpectValue(check_id)
            print(testcases_expect_value)

            print("第一步")
            li_dict = {}
            out_dict_keys = out_dict.keys()
            print("打印出所有keys")
            print(out_dict)
            print(out_dict_keys)

            # 如果已经存在相同的key;将value转换成列表，放置被替换
            if testcases_check_key in out_dict_keys:
                print("预期最后一步")
                print("已存在")
                print(out_dict[testcases_check_key])
                list_zh = []
                list_zh.append(out_dict[testcases_check_key])
                dict_zh = {}
                dict_zh[testcases_check_condition] = testcases_expect_value
                list_zh.append(dict_zh)
                out_dict[testcases_check_key] = list_zh
            else:
                #     key不存在重复直接存储成字典的形式
                print("第二步！")
                li_dict[testcases_check_condition] = testcases_expect_value
                out_dict[testcases_check_key] = li_dict
        print(out_dict)
        print("马嘉璐注意结果哟！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！1")


        # 4.用例入参表取值

        param_key_dict = {}
        print("test_interfaces_datas[1]===================================")
        print(test_interfaces_datas[1])
        for n in test_interfaces_datas[1]:  # ['accountName', '0', '0', '']

            if n[2] == "0":  # 无随机数，数据库取值
                testcases_param_values = Interface_Case_Param.getTestcasesParamValues(testcase_id,n[0])
                print("用例参数值")
                print(testcases_param_values)


                param_key_list = []
                for i in n:
                    param_key_list.append(i)
                param_key_list.append(testcases_param_values[0]['param_value'])
                # print(param_key_list)
                if param_key_list[1] == "0" or param_key_list[1] == "String":#字符串
                    param_key_dict[param_key_list[0]] = param_key_list[4]
                elif param_key_list[1] == '3' or param_key_list[1] == 'List':#列表
                    param_key_dict[param_key_list[0]] = eval(param_key_list[4])

            elif n[2] == "1": #有随机数
                random_values = eval(test_interfaces_datas[0]['interface_data']['param_data'])[n[0]]
                param_key_dict[n[0]] = random_values

        print("测试案例id=%s的测试用例入参值为%s" % (testcase_id, param_key_dict))

        # 6.执行条件
        testcases_action_condition = Interfaces_Case.getActionCondition(testcase_id)
        print("测试案例id=%s的执行条件为%s" % (testcase_id, testcases_action_condition))
    else:  #数据校验
        pass



    # 6.测试案例拼接数据
    interface_case_data = {}
    interface_case_data['id'] = int(testcase_id)
    interface_case_data['case_name'] = testcases_case_name
    interface_case_data['case_type'] = testcases_case_type
    interface_case_data['check_type'] = testcases_check_type
    interface_case_data['action_condition'] = testcases_action_condition
    interface_case_data['assert_response'] = out_dict
    interface_case_data['param_testcase_data'] = param_key_dict


    content = {
        'Querytestcases':interface_case_data
    }

    return content

def data_view(interface_case_data,test_interfaces_datas,environment_data):
    # 1.整体拼接:接口+测试案例+环境变量
    data = []
    data.append(environment_data)
    data.append(test_interfaces_datas[0]['interface_data'])
    data.append(interface_case_data)

    return data


# 测试案例取值
def testcasedata_view(test_case_toll_datas):

    # 1.取出url
    url = test_case_toll_datas[0]['environment_address']+test_case_toll_datas[1]['api']
    # 2.取出方式
    request_way = test_case_toll_datas[1]['method']

    # 3.取出加密解密url
    interfaces_encryption_url = test_case_toll_datas[1]['interfaces_encryption_url']
    interfaces_decrypt_url =  test_case_toll_datas[1]['interfaces_decrypt_url']

    interfaces_authentication = test_case_toll_datas[1]['interfaces_authentication']

    # 4.取测试案例数据（测试案例id+测试案例名称+数据+校验分类+请求头+断言）
    interfaces_id = test_case_toll_datas[1]['interfaces_id']
    testcases_id = test_case_toll_datas[2]['Querytestcases']['id']
    testcases_name = test_case_toll_datas[2]['Querytestcases']['case_name']
    param_testcase_data = test_case_toll_datas[2]['Querytestcases']['param_testcase_data']
    header = test_case_toll_datas[1]['header_key']
    assert_response = test_case_toll_datas[2]['Querytestcases']['assert_response']
    action_condition = test_case_toll_datas[2]['Querytestcases']['action_condition']

    # 5.取出请求方式
    testcases_apihttptype = test_case_toll_datas[1]["testcases_apihttptype"]
    print(test_case_toll_datas)
    # isList取值
    testcases_isList = test_case_toll_datas[1]["testcases_isList"]
    print(testcases_isList)
    # listPadding取值
    testcases_listPadding = test_case_toll_datas[1]["testcases_listPadding"]
    print(testcases_listPadding)


    content = {
        'interfaces_id':interfaces_id,
        'testcases_id':testcases_id,
        'testcases_name':testcases_name,
        'url':url,
        'request_way':request_way,
        'header':header,
        'assert_response':assert_response,
        'param_testcase_data': param_testcase_data,
        'interfaces_encryption_url' :interfaces_encryption_url,
        'interfaces_decrypt_url':interfaces_decrypt_url,
        'interfaces_authentication':interfaces_authentication,
        'action_condition':action_condition,
        'testcases_apihttptype' : testcases_apihttptype,
        'testcases_isList':testcases_isList,
        'testcases_listPadding':testcases_listPadding

    }

    return content

# 涉及到json数据传递的时候，存在嵌套，导致json数据不正确，返回值信息就不正确==>去除粘贴过来时存在的换行
# def json_data(content):
#     content = json.loads(content['testcases_datas']['data'])
#     return content

